using UnityEngine;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// Used for ajusting quintic bezier in editor.
/// NOTE: This script is used in edit mode ONLY!!!
/// </summary>
[ExecuteInEditMode]
public class PathBehaviour : SolidColorGizmo
{
	public int sampleTimes
	{
		set 
		{
			m_sampleTimes = value;
			if (m_bezier != null)
			{
				m_bezier.Sample (m_sampleTimes);
			}
		}
		get 
		{
			return m_sampleTimes; 
		}
	}
	
	public PathQuinticBezier bezier 
	{
		get { return m_bezier; }
	}
	
	public bool curveCreated 
	{
		get { return m_curveCreated; }
	}
	
	public Vector3 startAnchor
	{
		set
		{
			if (m_startAnchorSet) return;
			
			m_startAnchorSet = true;
			m_startAnchor = value;
		}
	}
	
	public bool startAnchorSet
	{
		get 
		{
			return m_startAnchorSet;
		}
	}	
	
	public Vector3 endAnchor 
	{
		set
		{
			if (m_endAnchorSet) return;
			
			m_endAnchorSet = true;
			m_endAnchor = value;
			
			m_bezier = new PathQuinticBezier (m_startAnchor, m_endAnchor);
			m_bezier.Sample (m_sampleTimes);
			m_anchorObjects = new List<GameObject> ();
			for (int i = 0, len = m_bezier.anchorCount; i < len; ++ i)
			{
				GameObject anchorHost = new GameObject ("P" + i);
				anchorHost.transform.parent = gameObject.transform;
				anchorHost.transform.position = m_bezier.GetAnchor (i);
				m_anchorObjects.Add (anchorHost);
			}
			
			m_curveCreated = true;
		}
	}
	
	public bool endAnchorSet
	{
		get
		{
			return m_endAnchorSet;
		}
	}
	
	protected override void DrawGizmos ()
	{
		if (curveCreated)
		{
			m_bezier.Render ();	
		}
	}
	
	void Update ()
	{
		if (m_bezier != null)
		{
			bool anchorPosChanged = false;
			
			for (int i = 0, len = m_bezier.anchorCount; i < len; ++ i)
			{
				Vector3 anchorPos = m_anchorObjects[i].transform.position;
				bool currentAnchorChanged = !(m_bezier.GetAnchor (i).Equals (anchorPos));
				
				if (currentAnchorChanged)
				{
					m_bezier.SetAnchor (i, anchorPos);
				}
				
				anchorPosChanged |= currentAnchorChanged;
			}
			
			if (anchorPosChanged)
			{
				m_bezier.Sample (m_sampleTimes);
			}
		}
	}
	
	[SerializeField]
	PathQuinticBezier m_bezier = null;
	
	[SerializeField]
	bool m_curveCreated = false;
	
	[SerializeField]
	Vector3 m_startAnchor = Vector3.zero;
	
	[SerializeField]
	bool m_startAnchorSet = false;
	
	[SerializeField]
	Vector3 m_endAnchor = Vector3.zero;
	
	[SerializeField]
	bool m_endAnchorSet = false;
	
	[SerializeField]
	List<GameObject> m_anchorObjects;
	
	[SerializeField]
	int m_sampleTimes = 500;
}

